/*
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\lib\ui\UdFormControls\UdMonthPicker\UdMonthPicker.tsx
 * @Date: 2021-12-07 14:32:07
 * @LastEditTime: 2021-12-07 14:44:12
 */
import _ from 'lodash'
import React, { PureComponent } from 'react'
import { DatePicker } from 'antd'
import { IUdFormItem } from '../../..'
import moment from 'moment'
import 'moment/locale/zh-cn.js'
import { MonthPickerProps } from 'antd/lib/date-picker/interface'

moment.locale('zh-cn')

const { MonthPicker } = DatePicker

class UdMonthPicker extends PureComponent<IUdMonthPickerProps, IUdMonthPickerState> {

    constructor(props: IUdMonthPickerProps) {
        super(props);
        this.state = {
            values: null,
        }
    }

    componentDidMount() {
        this.handleProps(this.props)
    }

    componentWillReceiveProps(nextProps: Readonly<IUdMonthPickerProps>) {
        this.handleProps(nextProps)
    }

    render() {
        //const { format } = this.props
        let values: any = {}

        if (this.state.values != null) {
            values.value = this.state.values
        }
        return (
            <MonthPicker className="ud-month-picker" {...this.props}
                onChange={this.triggerChange} format='YYYY年MM月' {...values} />
        )
    }

    private handleProps = (props: IUdMonthPickerProps) => {
        if (props.value && props.value !== '') {
            this.setState({ values: moment(props.value) })
        } else {
            this.setState({ values: null })
        }
    }

    private triggerChange = (value: any) => {
        //let format = this.props.format ? this.props.format : 'YYYY-MM'
        let format = 'YYYY-MM'
        this.props.onChange(value ? value.format(format) : null)
    }

}

interface IUdMonthPickerProps extends Partial<IUdFormItem>, MonthPickerProps {
    id?: string
    format?: string
    value?: any
    onChange?(value: any): void
}


interface IUdMonthPickerState {
    values?: any
}

export default UdMonthPicker
